<?php
class PartnerUserModel
{
    private $app_conf;
    private $conf;
    private $partner_api_class_name;
    private $partner_name;
    public function __construct($partner_name)
    {
        $this->conf = new ConfLib();
        $this->partner_name = $partner_name;
        switch($partner_name) {
            case 'douban' :
                $this->partner_api_class_name = 'Douban_Apiv2';
                break;
            case 'qq' :
                $this->partner_api_class_name = 'QQ_Api';
                break;
        }
        $class_name = StrLib::firstToUpper($partner_name) . 'UserDb';
        $this->partner_user_db = new $class_name ();
        $this->user_db = new UserDb();
        $this->app_conf = $this->conf->get($partner_name, 'app');
        $this->format_conf = $this->conf->get($partner_name, 'format');
    }

    public function isPartnerUserExsit($id)
    {
        $where = array(
            'id' => $id,
        );
        $r = $this->partner_user_db->selectCount($where);
        if(0 === $r) {
            return false;
        } else {
            return true;
        }
    }

    public function setUser($data)
    {
        $partner_user_id = $data['id'];
        if($this->isPartnerUserExsit($partner_user_id)) {
            $where = array(
                'id' => $partner_user_id,
            );
            unset($data['id']);
            $this->partner_user_db->update($data, $where);
            $where = array(
                $this->partner_name . '_user_id' => $partner_user_id,
            );
            $this->user_db->update($data, $where);
            $r = $this->user_db->selectRow($where);
            $id = $r['id'];
        } else {
            $data['passkey'] = md5($data['id'] . time() . rand(100, 10000));
            $this->partner_user_db->insertRow($data);
            $data[$this->partner_name . '_user_id'] = $data['id'];
            unset($data['id']);
            $id = $this->user_db->insertRow($data);
        }
        return $id;
    }

    public function getMe($code)
    {
        $partner = new $this->partner_api_class_name ($this->app_conf, array(), $this->format_conf);
        $tokens = $partner->getToken($code);
        $partner->setUser($tokens);
        $user = $partner->getMe();
        return array_merge($tokens, $user);
    }
}
?>
